package cn.jdemo.guava.RateLimiter;

import com.google.common.util.concurrent.RateLimiter;

import java.time.Duration;

/**
 * @see RateLimiter#create(double) 每秒产生许可数量
 *
 * 1.rateLimiter.acquire(1);
 * 如果要对QPS进行限制，那么Permit = Query，一次Query消耗一个Permit就能达到效果
 * 2.rateLimiter.acquire(packet.length);
 * 如果对文件网络IO进行限制，那么Permit = Size of Package，每次包大小越大消耗的Permit越多
 * 3.todo
 * 如果要对请求时长进行限制，那么Permit = Time Cost of Query
 */
public class Demo {
    public static void main(String[] args) {
        test1();
    }

    /**
     * 限流
     */
    private static void test1() {
        RateLimiter limiter = RateLimiter.create(100);// 每秒100
        for (int i = 0; i < 100; i++) {
            boolean b = limiter.tryAcquire(50, Duration.ofMillis(500L));
            if (b){
                System.out.println("业务执行："+i);
            }
        }
    }

    /**
     * 限流+热启动
     */
    private static void test2() {
        RateLimiter limiter = RateLimiter.create(100);// 每秒100
        for (int i = 0; i < 100; i++) {
            boolean b = limiter.tryAcquire(50, Duration.ofMillis(500L));
            if (b){
                System.out.println("业务执行："+i);
            }
        }
    }
}
